<template>
    <el-upload
    class="avatar-uploader"
    action="https://localhost:7083/api/File/PostFile"
    method="POST"
    :headers="{'Authorization' : Authorization}"
    :show-file-list="false"
    :on-success="handleAvatarSuccess"
    :before-upload="beforeAvatarUpload"
  >
    <img v-if="imageUrl" :src="imageUrl" class="avatar" />
    <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
  </el-upload>
</template>

<script lang="js">
import { UploadFilled, Plus } from '@element-plus/icons-vue'
import {ref} from "vue";
import {POSTA, PUTA} from "../../api";
import {ElMessage} from "element-plus";
import localstorage from '@/tools/localstorage';
import { UploadProps } from 'element-plus'
import {fileURL} from '@/config/baseConfig'

export default {
  name: "Upload",
  components: {
    UploadFilled,
    Plus
  },
  setup(prop, context) {
    const imageUrl = ref("");
    const user = localstorage.getItemObject("user")
    const Authorization = localstorage.getItemObject('Aut')

    const handleAvatarSuccess = (
      response,
      uploadFile
    ) => {
      console.log(response)
      PUTA(`User/UserUpdateAvatar?id=${user.Id}&avatar=${fileURL+ "/" + response}`).then(res => {
        console.log(res)
        ElMessage.success("上传成功")
        context.emit('eventParent', false)
      }).catch(err => {
        console.log(err)
      })
      // imageUrl.value = URL.createObjectURL(uploadFile.raw!)
    }

    const beforeAvatarUpload = (rawFile) => {
      // if (rawFile.type !== 'image/jpeg') {
      //   ElMessage.error('Avatar picture must be JPG format!')
      //   return false
      // } else if (rawFile.size / 1024 / 1024 > 2) {
      //   ElMessage.error('Avatar picture size can not exceed 2MB!')
      //   return false
      // }
      return true
    }

    return {
      imageUrl,
      beforeAvatarUpload,
      handleAvatarSuccess,
      Authorization
    }
  }
}

</script>

<style lang="scss" scoped>
</style>